package algorthm.systemTraning.binaryTree;
import java.util.*;
public class BinaryTreeLevelOrderTraversal {
    public static class TreeNode {
    public int val;
    public TreeNode left;
    public TreeNode right;
        TreeNode(int x) {
            val = x;
        }
    }
 
 
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
 
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
 
        while (!queue.isEmpty()) {
            List<Integer> level = new ArrayList<>();
            int currentLevelSize = queue.size();
            
            // 遍历当前层的每个节点
            for (int i = 0; i < currentLevelSize; i++) {
                TreeNode currentNode = queue.poll();
                level.add(currentNode.val);
                
                if (currentNode.left != null) {
                    queue.offer(currentNode.left);
                }
                if (currentNode.right != null) {
                    queue.offer(currentNode.right);
                }
            }
            
            result.add(level);
        }
 
        return result;
    }
    
    public static void main(String[] args) {
        // 构建二叉树
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.right.left = new TreeNode(4);
        root.right.right = new TreeNode(5);
        
        BinaryTreeLevelOrderTraversal solution = new BinaryTreeLevelOrderTraversal();
        List<List<Integer>> levels = solution.levelOrder(root);
        
        // 打印每层的节点值
        for (List<Integer> level : levels) {
            System.out.println(level);
        }
    }
}